package config

import (
	"encoding/json"
	"os"
	"io/ioutil"
	"fmt"
	"log"
)

var config *Config = nil

var enviroment Enviroment
type Enviroment struct {
  Env string
  Gopath string
}

type Config struct {
	conf map[string]interface{}
}

func init() {
	//初始化config
	config = new(Config)
	//初始化map
	configMap := make(map[string]interface{})
	//获取环境变量
	env := os.Getenv("NODE_ENV")
  	gopath := os.Getenv("GOPATH")
  	if env == "" || gopath == "" {
    	log.Fatal("GOPATH and NODE_ENV are required")
  	}
	enviroment.Env = env
	enviroment.Gopath = gopath
	//读取配置文件
	fileBytes, err := ioutil.ReadFile(gopath + "/src/go-scripts/config/" + env + ".json")
	if err != nil {
		log.Fatal(err.Error())
	}
	//解析配置文件
	json.Unmarshal(fileBytes, &configMap)
	config.conf = configMap
	fmt.Println("初始化配置文件")
}

func GetConfig() *Config {
	return config
}

func GetEnviroment() Enviroment {
	return enviroment
}

func (r *Config) GetRedisConfig() map[string]interface{} {
	return r.conf["redis"].(map[string]interface{})
}

func (r *Config) GetMongoConfig() map[string]interface{} {
	return r.conf["mongodb"].(map[string]interface{})
}

func (r *Config) GetNodeServerUrl() string {
	return r.conf["node-server"].(string)
}

func (r *Config) GetMysqlConfig() map[string]interface{} {
	return r.conf["mysql"].(map[string]interface{})
}
